package com.suns.controller;

import com.suns.exception.BusinessException;
import com.suns.exception.SystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.time.LocalDateTime;

//异常拦截处理器(Result风格,aop思想,借助spring异常处理工具类)
@RestControllerAdvice// 定义此类为异常处理器
public class ProjectExceptionAdvice {
    private static final Logger log = LoggerFactory.getLogger(ProjectExceptionAdvice.class);
    @ExceptionHandler(Exception.class)
    public  Result handle(Exception e) {
        //记录日志
        LocalDateTime now = LocalDateTime.now();
        log.error("系统在 "+now+" 时出现异常: ",e);
        return new Result(Code.SYSTEM_ERR,e.getMessage(),"系统繁忙,请稍后重试!");
    }
    @ExceptionHandler(SystemException.class)//定义处理系统异常
    public Result doSystemException(SystemException ex) {
        //记录日志
        LocalDateTime now = LocalDateTime.now();
        log.error("系统在 "+now+" 时出现异常: ",ex);
        return new Result(ex.getCode(),ex.getMessage(),"系统维护中,请耐心等待!");
    }

    @ExceptionHandler(BusinessException.class)//定义处理业务异常
    public Result doBusinessException(BusinessException ex) {
        //记录日志
        LocalDateTime now = LocalDateTime.now();
        log.error("系统在 "+now+" 时出现异常: ",ex);
        return new Result(ex.getCode(),ex.getMessage(),"服务维护中,请耐心等待!");
    }
}
